package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.IUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
    private IUserService userService;
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session) {

        //获取手机号
        String phone = user.getPhone();
        //验证码随机生成
        String code = RandomUtil.randomNumbers(6);
        session.setAttribute(phone, code);
        System.out.println(code);
        //调用工具类发送短信
        //SMSUtils.sendSms(phone, code);
        return R.success("短信发送成功");
    }
    @PostMapping("/login")
    public R login(@RequestBody Map<String, String> map, HttpSession session) {

        //用户输入的验证码和手机号
        String phone = map.get("phone");
        String code = map.get("code");
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            return R.error("手机号或验证码不能为空");
        }

        //获取session中保存的验证码 key是手机号
        String codeInSession = (String) session.getAttribute(phone);

        //校验两个验证码是否相同，如果相同，登录成功 将用户数据存入session中 表名用户已经登录

        if (code.equals(codeInSession)) {
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone, phone);
            User one = userService.getOne(wrapper);
            //手机号没有注册，自动保存到User表中
            //先查询 select * from user where phone = ?
            //判断查询的用户为空，保存
            if (one == null) {
                one = new User();
                one.setPhone(phone);
                one.setStatus(1);
                userService.save(one);
            }
            session.setAttribute("loginUser", one);

            return R.success("登录成功");

        }
        //如果不同，则登录失败
        return R.error("登录失败");
    }
}
